package com.hit.basmath.interview.top_interview_questions.medium_collection.trees_and_graphs;

/**
 * 200. 岛屿数量
 * <p>
 * 给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
 * <p>
 * 岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
 * <p>
 * 此外，你可以假设该网格的四条边均被水包围。
 * <p>
 * 示例 1：
 * <p>
 * 输入：grid = [
 * ["1","1","1","1","0"],
 * ["1","1","0","1","0"],
 * ["1","1","0","0","0"],
 * ["0","0","0","0","0"]
 * ]
 * 输出：1
 * <p>
 * 示例 2：
 * <p>
 * 输入：grid = [
 * ["1","1","0","0","0"],
 * ["1","1","0","0","0"],
 * ["0","0","1","0","0"],
 * ["0","0","0","1","1"]
 * ]
 * 输出：3
 * <p>
 * 提示：
 * <p>
 * m == grid.length
 * n == grid[i].length
 * 1 <= m, n <= 300
 * grid[i][j] 的值为 '0' 或 '1'
 */
public class _200 {
    private static int gridLenght;
    private static int gridDepth;

    public static int numIslands(char[][] grid) {
        /**
         * Record island number
         */
        int count = 0;
        gridLenght = grid.length;
        if (gridLenght == 0) {
            return 0;
        }
        gridDepth = grid[0].length;
        for (int i = 0; i < gridLenght; i++) {
            for (int j = 0; j < gridDepth; j++)
                if (grid[i][j] == '1') {
                    dfsMark(grid, i, j);
                    ++count;
                }
        }
        return count;
    }

    private static void dfsMark(char[][] grid, int i, int j) {
        /**
         * When we are meet 4 edges of grid, return immediately
         */
        if (i < 0 || j < 0 || i >= gridLenght || j >= gridDepth || grid[i][j] != '1') {
            return;
        }
        grid[i][j] = '0';
        /**
         * This 4 iteration is handle current element's 4 edges
         */
        dfsMark(grid, i + 1, j);
        dfsMark(grid, i - 1, j);
        dfsMark(grid, i, j + 1);
        dfsMark(grid, i, j - 1);
    }

    public static void main(String[] args) {
        char[][] test1 = {
                {'1', '1', '1', '1', '0'},
                {'1', '1', '0', '1', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '0', '0', '0'}
        };
        char[][] test2 = {
                {'1', '1', '0', '0', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '1', '0', '0'},
                {'0', '0', '0', '1', '1'}
        };
        System.out.println("In this grid, island's number is " + _200.numIslands(test1));
        System.out.println("In this grid, island's number is " + _200.numIslands(test2));
    }
}
